package han.cirno.corrupt.modules.library

import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import han.cirno.corrupt.components.school.impl.fafu.FafuLibClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class LibraryViewModel @Inject constructor():ViewModel() {
    val nowPage = mutableIntStateOf(1)
    val totalPage= mutableIntStateOf(1)
    val searchStatus= mutableIntStateOf(0)
    val resultsList= mutableStateListOf <FafuLibClient.SearchResult>()

    val isAppendLoading= mutableStateOf(false)
    val isFirstLoading= mutableStateOf(false)
    val isContentLoading= mutableStateOf(false)
    val keyword= mutableStateOf("")

    val contentScreenBook= mutableStateOf(null as FafuLibClient.SearchResult?)
    val contentScreenContent= mutableStateOf(null as FafuLibClient.BookDetail?)

    fun performSearch() {
        totalPage.intValue=1
        nowPage.intValue=1
        searchStatus.intValue=1
        isFirstLoading.value=true
        resultsList.clear()
        load(true)
    }

    private fun load(first: Boolean){
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                return@withContext FafuLibClient.instance.requestSearch(
                    keyword.value,
                    nowPage.intValue)
            }.onSuccess {
                resultsList.addAll(it.results)
                totalPage.intValue=it.totalPages
                nowPage.intValue += 1
                if(first) {
                    searchStatus.intValue=if(it.results.isEmpty())3 else 2
                }
            }.onFailure {
                searchStatus.intValue=0
            }.run {
               isAppendLoading.value=false
                isFirstLoading.value=false
            }
        }
    }

    fun loadMore(){
        if (isAppendLoading.value)return
        if (nowPage.intValue > totalPage.intValue)return
        isAppendLoading.value=true
        load(false)
    }

    fun loadDetail(searchResult: FafuLibClient.SearchResult, finishCallback:()->Unit){
        isContentLoading.value=true
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                return@withContext FafuLibClient.instance.requestDetail(searchResult.requestParam)
            }.onSuccess {
                contentScreenContent.value=it
                contentScreenBook.value=searchResult
                finishCallback()
            }.onFailure {

            }.run {
                isContentLoading.value=false
            }
        }
    }
}